define(function(require, exports, module){
	require("resource/js/easyui/themes/icon.css");
	require("resource/js/easyui/easyloader.js");
	require("resource/js/component/rules.js");
	var AJAX = require("resource/js/component/ajax.js");
	var CONST = require("resource/js/config/const.js");
	var E = require("resource/js/component/easyutil.js");
	var EC = require("resource/js/component/easycombobox.js");
	EC.create({
		url:BASEPATH+"/base/authoriza/basecode/getType.htm",
		param:{checkeds:"status,systype,deptType,con_scheduler"}
	});
	var userModel ;
	var obj={};
	var config =function(){
		return{
			type:"dept",
			name:'组织架构',
			column:[[
				        {field:'deptId',title:obj.get('base.dept.js.dept.departmentID'),width:100,align:'center',height:50,hidden:true},
				        {field:'deptCode',title:obj.get('base.dept.js.dept.departmentCode'),width:100,align:'center',height:50,hidden:true},
				        {field:'deptName',title:'组织名称',width:100,align:'center',height:50},
				        {field:'deptParent',title:'上级组织',width:100,align:'center',height:50,hidden:true},
				        {field:'deptParentName',title:'上级组织',width:100,align:'center',height:50},
				        {field:'deptTypeName',title:'施工状态',width:100,align:'center',height:50},
				        
				        {field:'operTimer',title:obj.get('base.dept.js.dept.operationTime'),width:100,align:'center',height:50}
				        ]]
		};
	}
	var dgutil = undefined;
	var datagridconfig = undefined;
	function initPage(){
		initDeptTree();
		EC.init({ ele:"#searchState",prompt:obj.get("base.dept.js.dept.pleaseSelectTheAvailableState"), grouptype:"status", value:"0"});
		EC.init({ ele:"#searchDeptType",prompt:obj.get("base.dept.js.dept.pleaseChooseTheNatureOfTheDepartment"), grouptype:"deptType" });
		dgutil = new E.ajaxDataGrid(datagridconfig);
		initSelParentDept('searchDeptParentName','searchDeptParent');
	}
	var initSelParentDept=function(textName,valName,systype,row){
		if(systype==undefined||systype==null){
			systype = '';
		}
		var currentDept="";
		if(row){
			//console.log(row);
			$("#"+valName).val(row.deptParent);
			currentDept = row.deptId;
		}else{
			$("#"+valName).val('');
		}
		$("#"+textName).textbox({
			buttonText: '上级组织选择',
			prompt:'',
			/*icons:[{
				iconCls:'icon-clear',
				handler: function(e){
					$("#"+valName).val('');
					$("#"+textName).textbox('setValue', '');
				}
			}],*/
			onClickButton:function(){
				$("#treeselecter1").dialog("open");
				using("ztree",function(){
					/*if($('#treeselecter1').dialog('options').isLoad){
						return;
					}*/
					var T = require("resource/js/component/treeutil.js");
					var tree = new T.ajaxTree({
						eid:"treeselecter1",
						url:BASEPATH+"/base/authoriza/dept/getTreeall.htm?status=0&systype="+systype,
						check:"radio",
						title:obj.get("base.dept.js.dept.departmentSelection"),
						checks:[$("#"+valName).val()],
						disable:function(node){
							if(node.id==currentDept){
								node.nocheck=true;
							}
							return false;
						},
						autoclose:false,
						save:function(data){
							var msg = "";
							if(textName!="add_deptParentName"){
								msg = validateDeptParent();
							}
							if(msg!=""){
								$.messager.confirm(obj.get("dept.systemHints"),msg,function(r){
							    	if(r){
							    		$("#"+textName).textbox("setValue",data[0].name);
										$("#"+valName).val(data[0].id);
										$('#treeselecter1').dialog('close');
									}
								});
							}else{
								$("#"+textName).textbox("setValue",data[0].name);
								$("#"+valName).val(data[0].id);
								$('#treeselecter1').dialog('close');
							}
						}
					});
					tree.load(function(obj){
						if($("#"+valName).val()!=""){
							var node = obj.getNodeByParam("id", $("#"+valName).val(), null);
							if(node){
								$("#"+textName).textbox("setValue",node.name);
							}
						}
					});
				});
			}
		});
		if(row){
			$("#"+textName).textbox('setValue', row.deptParentName);
		}else{
			$("#"+textName).textbox('setValue', '');
		}
	}
	var initDeptTree=function(){
		require("resource/js/component/tree.js");
		using('menu',function(){
			$("#deptTree").tree({
				searchable:false,
				title:'组织架构',
				url:BASEPATH+"/base/authoriza/dept/getTreeall.htm?status=0",
				setting:{
					menu:{
						enable:true,
						items:['refresh','showchild']
					},
					callback:{
						onClick:function(event, treeId, treeNode){
							$("#searchDeptParent").val(treeNode.id);
							$("#searchDeptParentName").textbox('setValue',treeNode.name);
							dgutil.pager(1);
						}
					},
					async:{
						showRefresh:true,
						enable:true,
						autoParam:["text=type","id"],
						url:BASEPATH+"/base/authoriza/dept/getTreeall.htm?status=0",
						type:"get"
					}
				}
			});
		});
	}
	//角色分配按钮事件
	var roleDialogInit = function(baseUrl,rows){
		var deptId = rows.deptId;
		var url = BASEPATH+"/base/authoriza/role/getRoleByDept.htm";
		var ajax = AJAX.init();
		var intiRoleTree = function(code,msg,data){
			var checks = [];
			var regexp = "";
			if(data!=undefined&&data.length>0){
				for(var k=0;k<data.length;k++){
					checks[k] = data[k].roleId;
					if(data[k].regexp!=undefined&&data[k].regexp!=''){
						regexp = data[k].regexp;
					}
				}
			}
			$("#treeselecter").dialog("open");
			using("ztree",function(){
				var T = require("resource/js/component/treeutil.js");
				var tree = new T.ajaxTree({
					eid:"treeselecter",
					url:BASEPATH+"/base/authoriza/role/getTreeall.htm",
					check:"checkbox",
					title:obj.get("base.dept.js.dept.roleSelection"),
					checks:checks,
					save:function(data){
						var checks = '';
						for(var k=data.length-1;k>=0;k--){
							if(k==0) checks+=data[k].id;
							else checks+=data[k].id+",";
						}
						//var url = BASEPATH+"/base/authoriza/dept/saveDeptRole.htm";
						AJAX.init().success(function(code,msg,data){
							if(data){
								$.messager.show({ title:obj.get("base.dept.js.dept.systemHints"), msg:obj.get("base.dept.js.dept.saveSuccess"), timeout:5000, showType:'slide' });
							}
						}).error(function(code,msg,data){
							$.messager.show({ title:obj.get("base.dept.js.dept.systemHints"), msg:obj.get("base.dept.js.dept.saveFailure"), timeout:5000, showType:'slide' });
						}).post(baseUrl,{deptId:deptId,checkeds:checks});
					}
				});

				tree.setting.callback.beforeCheck=function(treeId, treeNode) {
					if(treeNode.checked)
						return true;
					else {
						var treeobj = this.getZTreeObj(treeId);
						treeobj.setting.check.chkboxType={ "Y": "ps", "N": "ps" }
						treeobj.checkNode(treeNode,false,true,false);
						treeobj.setting.check.chkboxType={ "Y": "", "N": "" }
						return true;
					}
				}
				tree.load();
			});
		}
		ajax.success(intiRoleTree).error(intiRoleTree).post(url,{deptId:deptId});
	}

	var onSelectSys=function(record){
		$("#deptParentName").ztreebox("options").onLoad = function(){
			var tree = $("#deptParentName").ztreebox("ztree");
			if($("#deptId").val()&&$("#deptId").val()!=""){
				var node = tree.getNodeByParam("id",$("#deptId").val());
				if(node){
					tree.setChkDisabled(node,true,false,true);
				}
			}
			var deptParent = $("#deptParentName").textbox('getValue');
			if(deptParent&&deptParent!=""){
				var node = tree.getNodeByParam("id",deptParent);
				if(!node){
					$("#deptParentName").textbox('setValue',record.deptParentName);
					$("#deptParentName").next().find("input[type='hidden']").val(deptParent);
				}
			}
		}
		$("#deptParentName").ztreebox("reload",BASEPATH+"/base/authoriza/dept/getTreeall.htm",{status:"0",systype:record.baseCode});
	}
	
	var addDialogInit = function(baseUrl,row){
		
		if(row.deptCode.length == 12){
			return;
		}
		
		$("#adddlg").dialog({
			iconCls: 'icon-save',
			title:config().name+obj.get("base.dept.js.dept.add"),
			href:baseUrl,
			onLoad:function(){
				if(row.deptCode.length == 8){
					/**
					 * 动态处理表单
					 */
					var str ="<tr>"+
							"<td class='key'><span></span>施工状态:</td>"+
							"<td><input class='easyui-combobox' type='text' id='deptType' name='deptType'  validType=\"\" data-options=\"prompt:''\"/></td>"+
							"</tr>";		
					$('#form_table').append(str);
					$.parser.parse('#form_table');
				}
				$("#add_deptParentName").textbox('setValue',row.deptName);
				$("#add_deptParent").val(row.deptId);
				EC.init({ ele:"#deptType",grouptype:"con_scheduler"});
		    },
		    
			buttons: [{
				text:obj.get("base.dept.js.dept.save"),
				iconCls:'icon-ok',
				accessKey:{akey:18,mkey:83},
				handler:function(){
					using(["form"],function(){
						if($("#addform").form("validate")){

							E.ajaxHandler(BASEPATH+'/base/authoriza/dept/save.htm',$("#addform").serializeJson(),function(){
								dgutil.pager();
								$("#adddlg").dialog("close");
							});	
						}
					});
				}
			},{
				text:obj.get("base.dept.js.dept.cancel"),
				addClass:'l-btn-red',iconCls:'icon-not',
				accessKey:{akey:18,mkey:67},
				handler:function(){
					$('#adddlg').dialog('close');
					$("#dd").tooltip("hide");
				}
			}]
		});
		$("#adddlg").dialog("open");
	}

	var updDialogInit = function(baseUrl,row){
		
		if(row.deptCode.length == 16){
			return;
		}
		
		$("#adddlg").dialog({
			iconCls: 'icon-save',
			title:config().name+obj.get("base.dept.js.dept.update"),
			href:baseUrl,
			onLoad:function(){
				using("form",function(){
					if(row.deptCode.length == 4){
						$(".for_hide").hide();
					}
					if(row.deptCode.length == 12){
						/**
						 * 动态处理表单
						 */
						var str ="<tr>"+
								"<td class='key'><span></span>施工状态:</td>"+
								"<td><input class='easyui-combobox' type='text' id='deptType' name='deptType'  validType=\"\" data-options=\"prompt:''\"/></td>"+
								"</tr>";		
						$('#form_table').append(str);
						$.parser.parse('#form_table');
					}
					$("#upd_deptParentName").textbox('setValue',row.deptParentName);
					$("#upd_deptParent").val(row.deptParent);
					EC.init({ ele:"#deptType",grouptype:"con_scheduler"});
					$('#updform').form('load',row);
				});
				$('.tooltip[tabindex="-1"]').remove();
		    },
			buttons: [{
				text:obj.get("base.dept.js.dept.save"),
				iconCls:'icon-ok',
				accessKey:{akey:18,mkey:83},
				handler:function(){
					using(["form"],function(){
						if($("#updform").form("validate")){
//							if($("#upd_deptParent").val()==""){
								E.ajaxHandler(BASEPATH+'/base/authoriza/dept/update.htm',$("#updform").serializeJson(),function(){
									dgutil.pager();
									$("#adddlg").dialog("close");
								});	
//							}
						}
					});
				}
			}/*,{
				text:'重置',
				accessKey:{akey:18,mkey:82},
				handler:function(){
					using("form",function(){
						$('#updform').form('load',row);
						

						EC.init({ ele:"#status",grouptype:"status",value:row.status});
						$("#deptParentName").ztreebox({});
		
						if(userModel.userType==CONST.USERTYPE.SUPERUSER){
							EC.init({ ele:"#systype",grouptype:"systype",value:row.systype,onSelect:onSelectSys});
							onSelectSys({baseCode:row.systype});
						}else{ //当前用户非超级管理员 系统类型和用户是一样
							EC.init({ ele:"#systype",grouptype:"systype",value:userModel.sysType,readonly:true});
							onSelectSys({baseCode:userModel.sysType});
							$("#systype").closest("tr").hide();
						}
					});
				}
			}*/,{
				text:obj.get("base.dept.js.dept.cancel"),
				addClass:'l-btn-red',iconCls:'icon-not',
				accessKey:{akey:18,mkey:67},
				handler:function(){
					$('#adddlg').dialog('close');
					$("#dd").tooltip("hide");
				}
			}]
		});
		$("#adddlg").dialog("open");
	}
	/**
	 * 校验当前用户所选上部门是否为当前部门的子级部门
	 * 如果是 则提示用户是否确定进行此操作 若确定 则将改修改为上部门的子部门的上部门改为修改为上部门的上部门
	 */
	var validateDeptParent =function(){
		var deptId = $("#deptId").val();
		var deptName = $("#deptName").val();
		var treeObj = $.fn.zTree.getZTreeObj("treeselecter1_tree");
		var nodes = treeObj.getCheckedNodes(true);
		var parent = nodes[0].getParentNode();
		if(parent=null||parent==undefined){
			return '';
		}
		var res = checktreeNodeParent(parent,deptId);
		var ppName = obj.get("base.dept.js.dept.firstLevelDepartment");
		if(res.pId!=null){
			ppName = res.getParentNode().name;
		}
		if(res!=null&&res.hasOwnProperty("id")){
			return obj.get("base.dept.js.dept.youConfirmThat")+'【'+nodes[0].name+'】'+obj.get("base.dept.js.dept.departmentChangedTo")+'【'+deptName+'】'+obj.get("base.dept.js.dept.isItTheDepartmentsUpperDepartment?IfItIsConfirmed")+'，【'+nodes[0].name+'】'+obj.get("base.dept.js.dept.theDepartmentWillBeUpgradedTo")+'【'+ppName+'】'+(res.pId!=null?obj.get("base.dept.js.dept.subDepartmentOfTheDepartment"):'');
			/*$.messager.confirm('系统提示','您确认将【'+nodes[0].name+'】部门改为【'+deptName+'】部门的上部门吗？如果确认，【'+nodes[0].name+'】部门将升级为【'+ppName+'】'+(res.pId!=null?'部门的子部门！':''),function(r){
			    	return true;
			});*/
		}else{
			return '';
		}
	}
	var checktreeNodeParent = function(parent,deptId){
		if(parent==null){
			return '';
		}
		if(parent.id==deptId){
			return parent;
		}else{
			if(parent.pId==null){
				return "";
			}
			return checktreeNodeParent(parent.getParentNode(),deptId);
		}
		
	}
	var areaInputTree = function(treeDialogId, areaNameInput, areaidInput){
		$("#" + areaNameInput).textbox({
			buttonText: obj.get("base.dept.js.dept.administrativeDivision"),
			prompt:obj.get("base.dept.js.dept.pleaseChooseTheAdministrativeDivision"),
			onClickButton:function(){
				function zTreeBeforeCheck(treeId, treeNode) {								
					if(treeNode.isparent){									
					       return false;
					}

				};
				$("#" + treeDialogId).dialog("open");
				var T = require("resource/js/component/treeutil.js");
				using("ztree",function(){
					if($('#' + treeDialogId).dialog('options').isLoad){
						return;
					}
					var tree = new T.ajaxTree({
						eid:treeDialogId,
						url:BASEPATH+"/base/authoriza/conmonData/queryData.htm?queryId=basearea",
						check:"radio",
						title:obj.get("base.dept.js.dept.administrativeDivision"),
						checks:[$("#" + areaidInput).val()],
						/*disable:function(node){
							if(node.id.length<10){
								return true;
							}
						},*/
						save:function(data){
							if(data[0].id!=''){
								$("#" + areaNameInput).textbox("setValue",data[0].name);
								$("#" + areaidInput).val(data[0].id);
							}else{
								return;
							}

						},
				        data: {
				    		simpleData: {
				    			enable: true,
				    			idKey:"id",
				    			pIdKey:"pid"
				    		}
				    	},
				    	callback:{
				    		beforeCheck: zTreeBeforeCheck
				    	}
					});
					tree.load(function(obj){
						var node = obj.getNodesByFilter(function(node){
							if(node.isparent){
								obj.setChkDisabled(node, true);
							}
						}, false);
						if($("#" + areaidInput).val()!=""){
							var node = obj.getNodeByParam("id", $("#" + areaidInput).val(), null);
							if(node){
								$("#" + areaNameInput).textbox("setValue",node.name);
							}
						}
					});
				});
			}
		});
	}
	
	var areaEditTree = function(){
		$("#editAreaName").textbox({
			buttonText: obj.get("base.dept.js.dept.administrativeDivision"),
			prompt:obj.get("base.dept.js.dept.pleaseChooseTheAdministrativeDivision"),
			onClickButton:function(){
				function zTreeBeforeCheck(treeId, treeNode) {								
					if(treeNode.isparent){									
					       return false;
					}

				};
				$("#treeselecter3").dialog("open");
				var T = require("resource/js/component/treeutil.js");
				using("ztree",function(){
					if($('#treeselecter3').dialog('options').isLoad){
						return;
					}
					var tree = new T.ajaxTree({
						eid:"treeselecter3",
						url:BASEPATH+"/base/authoriza/conmonData/queryData.htm?queryId=basearea",
						check:"radio",
						title:obj.get("base.dept.js.dept.administrativeDivision"),
						checks:[$("#areaId").val()],
						/*disable:function(node){
							if(node.id.length<10){
								return true;
							}
						},*/
						save:function(data){
							if(data[0].id!=''){
								$("#editAreaName").textbox("setValue",data[0].name);
								$("#editArea").val(data[0].id);
								/*if(data[0].getParentNode()&&data[0].getParentNode().getParentNode()){
									$.fn.mapbox.localtext=data[0].getParentNode().getParentNode().name+data[0].getParentNode().name;
								}else if(data[0].getParentNode()){
									$.fn.mapbox.localtext=data[0].getParentNode().name+data[0].name;
								}else{
									$.fn.mapbox.localtext=data[0].name;
								}*/
							}else{
								return;
							}

						},
				        data: {
				    		simpleData: {
				    			enable: true,
				    			idKey:"id",
				    			pIdKey:"pid"
				    		}
				    	},
				    	callback:{
				    		beforeCheck: zTreeBeforeCheck
				    	}
					});
					tree.load(function(obj){
						var node = obj.getNodesByFilter(function(node){
							if(node.isparent){
								obj.setChkDisabled(node, true);
							}
						}, false);
						if($("#editArea").val()!=""){
							var node = obj.getNodeByParam("id", $("#" + areaIdInput).val(), null);
							if(node){
								$("#editAreaName").textbox("setValue",node.name);
							}
						}
					});
				});
			}
		});
	}
	
	
	var delInit = function(baseUrl,rows){
		var checks = "";
		for(var key in rows){
			if(key==rows.length-1){
				checks += rows[key].deptId;
			}else{
				checks += rows[key].deptId+",";
			}
		}
		AJAX.init().success(function(){
			dgutil.delRow(rows);
		}).post(baseUrl,{checkeds:checks});
	}
	module.exports = {
		trans:function(id){
				var param=function(obj_){
					obj=obj_;
				var buttons ={ 
						title:{
							_class:"",
							text:obj.get("base.dept.js.dept.departmentList")
						},
						btn:[
					 {
						iconCls: 'icon-search',
						url:'/base/authoriza/dept/getByPaged.htm',
						text:obj.get("base.dept.js.dept.query"),
						addClass:'l-btn-display',
						handler:function(){dgutil.pager(1);}
					},{
						iconCls: 'icon-add',
						addClass:'l-btn-display',
						text:obj.get("base.dept.js.dept.add"),
						url:'/view/base/dept/add',
						handler: addDialogInit,
						needRow:true
					},
					 {
						iconCls: 'icon-edit',
						url:'/view/base/dept/upd',
						text:obj.get("base.dept.js.dept.update"),
						addClass:'l-btn-display',
						needRow:true,
						handler: updDialogInit
					},
					 {
						iconCls: 'icon-remove',
						url:'/base/authoriza/dept/delete.htm',
						text:obj.get("base.dept.js.dept.delete"),
						addClass:'l-btn-display',
						needRows:true,
						isCheck:true,
						handler: delInit
					}/*,
					{
						iconCls: 'icon-assign',
						url:'/base/authoriza/dept/saveDeptRole.htm',
						text:obj.get("base.dept.js.dept.roleAssignment"),
						needRow:true,
						addClass:'l-btn-display',
						handler: roleDialogInit
					}*/
					]};
					datagridconfig = {
							fitColumns:true,
							singleSelect:false,
							striped:true,
							autoRowHeight:false,
							fit: true,
							toolbar:buttons,
							columns:config().column,
							eid:"dg",
							autoLoad:true,
							url:BASEPATH+'/base/authoriza/dept/getByPaged.htm',
							args:"searchform",
							/*onLoadSuccess:function(data){
								debugger;
							}*/
					};
					using(["datagrid","ztreebox","parser","textbox","messager","dialog","combobox"],function(){
						initPage();
						/*$("#mycontainer").layout();*/
						indexApp.exec("user",function(user){
							userModel = user;
							//为用户增加系统类型
							var sysTypes = [];
							$.each(userModel.depts,function(i,item){
								sysTypes.push(item.systype);
							});
							userModel.sysTypes = sysTypes;
						});
					});
			}		
			loadI18n('base/dept',param);
		}
	
	}
});